<template>
  <div class="registration-container">
    <van-tabs
        v-model:active="activeTab"
        sticky
        @change="handleTabChange"
        animated
    >
      <van-tab title="全部" name="all">
        <div v-if="allRegistrationList.length > 0">
          <van-cell-group>
            <van-cell
                v-for="(item, index) in allRegistrationList"
                :key="index"
                :title="item.title"
                :label="item.label"
                is-link
                @click="handleRegistrationClick(item)"
            >
              <template #right-icon>
                <van-tag :type="getStatusType(item.status)">{{ item.status }}</van-tag>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
        <div v-else class="empty-tip">暂无挂号记录</div>
      </van-tab>
      <van-tab title="待付款" name="unpaid">
        <div v-if="unpaidRegistrationList.length > 0">
          <van-cell-group>
            <van-cell
                v-for="(item, index) in unpaidRegistrationList"
                :key="index"
                :title="item.title"
                :label="item.label"
                is-link
                @click="handleRegistrationClick(item)"
            >
              <template #right-icon>
                <van-tag type="warning">{{ item.status }}</van-tag>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
        <div v-else class="empty-tip">暂无待付款挂号记录</div>
      </van-tab>
      <van-tab title="待就诊" name="waiting">
        <div v-if="waitingRegistrationList.length > 0">
          <van-cell-group>
            <van-cell
                v-for="(item, index) in waitingRegistrationList"
                :key="index"
                :title="item.title"
                :label="item.label"
                is-link
                @click="handleRegistrationClick(item)"
            >
            </van-cell>
          </van-cell-group>
        </div>
        <div v-else class="empty-tip">暂无待就诊挂号记录</div>
      </van-tab>
      <van-tab title="已完成" name="completed">
        <div v-if="completedRegistrationList.length > 0">
          <van-cell-group>
            <van-cell
                v-for="(item, index) in completedRegistrationList"
                :key="index"
                :title="item.title"
                :label="item.label"
                is-link
                @click="handleRegistrationClick(item)"
            >
            </van-cell>
          </van-cell-group>
        </div>
        <div v-else class="empty-tip">暂无已完成挂号记录</div>
      </van-tab>
      <van-tab title="已取消" name="cancelled">
        <div v-if="cancelledRegistrationList.length > 0">
          <van-cell-group>
            <van-cell
                v-for="(item, index) in cancelledRegistrationList"
                :key="index"
                :title="item.title"
                :label="item.label"
                is-link
                @click="handleRegistrationClick(item)"
            >
            </van-cell>
          </van-cell-group>
        </div>
        <div v-else class="empty-tip">暂无已取消记录</div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { NavBar, Tabs, Tab, CellGroup, Cell, Tag, showToast } from 'vant';
import { getMyBookingsAPI } from '../../api/book/bookRequest.js';

const route = useRoute();
const router = useRouter();

// 注册 Vant 组件
const components = {
  VanNavBar: NavBar,
  VanTabs: Tabs,
  VanTab: Tab,
  VanCellGroup: CellGroup,
  VanCell: Cell,
  VanTag: Tag
};

// 使用字符串类型的 activeTab
const activeTab = ref('all');

// 返回上一页
const goBack = () => {
  router.push('/my');
};

// 处理标签页切换
const handleTabChange = (name) => {
  activeTab.value = name;
  // 更新路由参数，使用 replace 而不是 push
  router.replace({
    query: { ...route.query, tab: name }
  });
  updateLists();
};

// 监听路由变化
onMounted(() => {
  const tab = route.query.tab || 'all';
  activeTab.value = tab;
  updateLists();
});

// 监听路由参数变化
watch(() => route.query.tab, (newTab) => {
  if (newTab && newTab !== activeTab.value) {
    activeTab.value = newTab;
  }
}, { immediate: true });

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待付款':
      return 'warning';
    case '待就诊':
      return 'primary';
    case '已完成':
      return 'success';
    case '已取消':
      return 'danger';
    default:
      return 'default';
  }
};

// 定义状态列表
const allRegistrationList = ref([]);
const unpaidRegistrationList = ref([]);
const waitingRegistrationList = ref([]);
const completedRegistrationList = ref([]);
const cancelledRegistrationList = ref([]);

// 格式化预约记录数据
const formatBookingData = (booking) => {
  return {
    id: booking.bookingId,
    workId: booking.workId,
    ruleId: booking.ruleId,
    title: `预约号：${booking.bookingId}`,
    label: `就诊时间：${booking.scheduleDate} ${booking.startTime}-${booking.endTime}\n挂号费：${booking.price}元`,
    status: getStatusText(booking.status)
  };
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '已取消';
    case 1: return '待付款';
    case 2: return '待就诊';
    case 3: return '就诊中';
    case 4: return '已完成';
    default: return '未知状态';
  }
};

// 根据状态分类预约记录
const classifyBookings = (bookings) => {
  allRegistrationList.value = bookings.map(formatBookingData);
  unpaidRegistrationList.value = bookings.filter(b => b.status === 1).map(formatBookingData);
  waitingRegistrationList.value = bookings.filter(b => b.status === 2).map(formatBookingData);
  completedRegistrationList.value = bookings.filter(b => b.status === 4).map(formatBookingData);
  cancelledRegistrationList.value = bookings.filter(b => b.status === 0).map(formatBookingData);
};

// 处理挂号记录点击
const handleRegistrationClick = (item) => {
  console.log('点击挂号记录:', item);
  router.push({
    path: '/bookingDetail',
    query: {
      bookingId: item.id
    }
  });
};

// 监听路由变化，更新列表
watch(() => route.query.refresh, (newVal) => {
  if (newVal === 'true') {
    // 更新列表数据
    updateLists();
  }
}, { immediate: true });

// 更新列表数据
const updateLists = async () => {
  try {
    const status = activeTab.value === 'all' ? -1 :
      activeTab.value === 'unpaid' ? 1 :
      activeTab.value === 'waiting' ? 2 :
      activeTab.value === 'completed' ? 4 :
      activeTab.value === 'cancelled' ? 0 : -1;
    
    const response = await getMyBookingsAPI(status);
    if (response.success) {
      classifyBookings(response.data);
    } else {
      showToast('获取预约记录失败');
    }
  } catch (error) {
    console.error('获取预约记录失败:', error);
    showToast('获取预约记录失败');
  }
};
</script>

<style scoped>
.registration-container {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.empty-tip {
  text-align: center;
  color: #969799;
  padding: 32px 0;
  font-size: 14px;
}

:deep(.van-tabs__wrap) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

:deep(.van-tab--active) {
  font-weight: bold;
}
</style>